package com.gaogzhen.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.Market;
import com.gaogzhen.domain.UserFavoriteMarket;
import com.gaogzhen.mapper.UserFavoriteMarketMapper;
import com.gaogzhen.model.RRException;
import com.gaogzhen.service.MarketService;
import com.gaogzhen.service.UserFavoriteMarketService;
import com.gaogzhen.utils.SqlExecuteUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @date 2022-12-10 17:09
*/
@Service
public class UserFavoriteMarketServiceImpl extends ServiceImpl<UserFavoriteMarketMapper, UserFavoriteMarket> implements UserFavoriteMarketService{

    @Autowired
    private MarketService marketService;

    @Autowired
    private Snowflake snowflake;

    @Override
    public void addFavorite(Long userId, Market market) {
        UserFavoriteMarket userFavoriteMarket = new UserFavoriteMarket();
        userFavoriteMarket.setUserId(userId);
        Byte type = market.getType();
        userFavoriteMarket.setType(type.intValue());
        String symbol = market.getSymbol();
        Market market1 = marketService.getBySymbol(symbol);
        userFavoriteMarket.setMarketId(market1.getId());
        userFavoriteMarket.setId(snowflake.nextId());
        SqlExecuteUtils.sqlExceptionHandler(this::save, userFavoriteMarket, "用户收藏市场失败");
    }

    @Override
    public void cancelFavorite(Long userId, String symbol) {
        Market market = marketService.getBySymbol(symbol);
        boolean remove = remove(new LambdaQueryWrapper<UserFavoriteMarket>()
                .eq(UserFavoriteMarket::getUserId, userId)
                .eq(UserFavoriteMarket::getMarketId, market.getId())
        );
        if (!remove) {
            throw new RRException("取消收藏失败");
        }
    }
}
